/**
 * 
 */
package com.regedit.aplicacion.communication;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

/**
 * @author pjohnson
 * 
 */
public class RequestHttp {

	private static HttpURLConnection connection;
	public static final boolean METHOD_GET = true;

	private RequestHttp() {
	}

	/**
	 * Perform an HTTP GET or POST with HttpUrlConnection.
	 * 
	 * @param urlService
	 *            the URL service
	 * @param method
	 *            the method
	 * @return String the result from the server
	 * @method String method to use
	 */
	public synchronized static String httpResponseString(String urlService,
			final boolean method, String postData) {
		
		InputStream input = httpResponse(urlService, method, postData);
		

		String httpResponse;
		if (input != null) {
			String line = null;
			final StringBuilder sBuilder = new StringBuilder();
			BufferedReader bReader;
			try {
				bReader = new BufferedReader(new InputStreamReader(input,
						"ISO-8859-1"));
				while ((line = bReader.readLine()) != null) {
					sBuilder.append(line + '\n');
				}
				httpResponse = sBuilder.toString();
			} catch (UnsupportedEncodingException e1) {
				httpResponse = "";
				Log.e("error", e1.getMessage());
			} catch (IOException e) {
				httpResponse = "";
				Log.e("error", e.getMessage());
			} finally {
				// Close the connection, set all objects to null
				if (connection != null) {
					connection.disconnect();
				}
				bReader = null;
				connection = null;
			}
		} else {
			httpResponse = "";
		}
		return httpResponse;
	}

	// TODO:javadoc
	public static synchronized Bitmap httpResponseBitmap(
			final String urlService, final boolean method) {

		InputStream input = httpResponse(urlService, method, null);
		Bitmap bitmap;
		if (input != null) {
			try {
				bitmap = BitmapFactory.decodeStream(input, null, null);
				input.close();
			} catch (IOException e1) {
				bitmap = null;
				Log.e("error", e1.getMessage());
			} finally {
				// Close the connection, set all objects to null
				if (connection != null) {
					connection.disconnect();
				}
				connection = null;
			}
		} else {
			bitmap = null;
		}
		return bitmap;
	}

	// TODO:javadoc
	private static synchronized InputStream httpResponse(
			final String urlService, final boolean method,
			final String postString) {
		connection = null;
		String methodConnection;
		if (method == METHOD_GET) {
			methodConnection = "GET";
		} else {
			methodConnection = "POST";
		}
		InputStream inputStream;
		URL serverAddress = null;
		try {
			serverAddress = new URL(urlService);
			// Set up the initial connection
			connection = (HttpURLConnection) serverAddress.openConnection();
//			if (connection instanceof HttpsURLConnection) {}
			connection.setReadTimeout(0);
			connection.setRequestMethod(methodConnection);
			if (!method) {// Si es Post
				connection.setDoOutput(true);
				final String boundry = "SeguriappBoundrySC";// -----xxxxxxxBOUNDERxxxxdsx";
				connection.setRequestProperty("Content-Type",
						"multipart/related; boundary=" + boundry);
				connection.setRequestProperty("MIME-version", "1.0");
				OutputStream stream;

				stream = connection.getOutputStream();
				stream.write(postString.getBytes());
				stream.close();
			}

			connection.connect();

			// Read the result from the server
			inputStream = connection.getInputStream();

		} catch (final Exception ex) {
			// Close the connection, set all objects to null
			if (connection != null) {
				connection.disconnect();
			}
			inputStream = null;
			// Log.e("response","crashed " + urlService);
			Log.e("error", ex.getMessage());
		}
		return inputStream;
	}

}
